﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using HalconDotNet;

namespace 多尺度相机采集
{
    public partial class CamControlPanel : UserControl
    {
        Camera myCamera;
        HObject m_Image;
        public HTuple hv_WindowHandle = null;
        private bool isOpened = false, isGrabing = false, firstTime = true;

        public CamControlPanel(string name)
        {
            //使用双缓冲，让图像显示不闪烁
            SetStyle(
                     ControlStyles.OptimizedDoubleBuffer
                     | ControlStyles.ResizeRedraw
                     | ControlStyles.Selectable
                     | ControlStyles.AllPaintingInWmPaint
                     | ControlStyles.UserPaint
                     | ControlStyles.SupportsTransparentBackColor,
                     true);
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            camName.Text += name;
            myCamera = new Camera(name);
            Thread mainThread = new Thread(MainRun);
            mainThread.IsBackground = true;
            mainThread.Start();
        }

        private void MainRun()
        {
            while (true)
            {
                if (!isOpened)
                    continue;
                if (isGrabing)
                {
                    //m_Image = myCamera.GrabImage();
                    //myCamera.DispayImage(m_Image, hWindowControl1, ref hv_WindowHandle);
                    //Invoke(new Action(() =>
                    //{
                    //    label1.Text = hv_WindowHandle.ToString();
                    //}));

                }

            }
        }

        private void Btn_OpenCam_Click(object sender, EventArgs e)
        {
            if (isOpened)
                return;
            myCamera.OpenCamera();
            isOpened = true;
        }

        private void Btn_CloseCam_Click(object sender, EventArgs e)
        {
            if (!isOpened)
                return;
            myCamera.CloseCamera();
            isOpened = false;
        }

        private void Btn_SaveImg_Click(object sender, EventArgs e)
        {
            myCamera.SaveImage(m_Image);
        }

        private void CamControlPanel_Load(object sender, EventArgs e)
        {

        }

        private void Btn_StartGrab_Click(object sender, EventArgs e)
        {
            if (Btn_StartGrab.Text == "开始采集")
            {
                isGrabing = true;
                Btn_StartGrab.Text = "停止采集";
            }
            else
            {
                isGrabing = false;
                Btn_StartGrab.Text = "开始采集";
            }
        }

        ~CamControlPanel()
        {
            myCamera.CloseCamera();
        }
    }
}
